package com.liujit.auth.security.handler;

import com.liujit.common.domain.result.Result;
import com.liujit.common.enums.ResultCode;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author: liujun
 * @date: 2021/6/21 10:55 下午
 * @description: 全局异常拦截
 */
@RestControllerAdvice
public class AuthExceptionHandler {

    /**
     * 未知请求来源，非法请求
     *
     * @param e
     * @return
     * @author: liujun
     * @date: 2021/6/21 10:56 下午
     */
    @ExceptionHandler(NoSuchClientException.class)
    public Result handleNoSuchClientException(NoSuchClientException e) {
        return Result.failure(ResultCode.INTERFACE_ILLEGAL_REQUEST);
    }

    /**
     * 用户不存在
     *
     * @param e
     * @return
     * @author: liujun
     * @date: 2021/6/21 10:56 下午
     */
    @ExceptionHandler(UsernameNotFoundException.class)
    public Result handleUsernameNotFoundException(UsernameNotFoundException e) {
        return Result.failure(ResultCode.USER_NOT_EXIST);
    }

    /***
     * 用户名和密码异常
     * @param e
     * @return
     * @author: liujun
     * @date: 2021/6/21 10:56 下午
     */
    @ExceptionHandler(InvalidGrantException.class)
    public Result handleInvalidGrantException(InvalidGrantException e) {
        return Result.failure(ResultCode.USER_ACCOUNT_ERROR);
    }

    /**
     * 账户异常(禁用、锁定、过期)
     *
     * @param e
     * @return
     * @author: liujun
     * @date: 2021/6/21 10:56 下午
     */
    @ExceptionHandler({ InternalAuthenticationServiceException.class })
    public Result handleInternalAuthenticationServiceException(InternalAuthenticationServiceException e) {
        return Result.failure(ResultCode.USER_ACCOUNT_DISABLE);
    }
}
